package com.qingzhuge.manager.autoconfigure;

import com.qingzhuge.common.IBaseEnum;
import com.qingzhuge.autoconfigure.QingTingProperties;
import com.qingzhuge.sys.entity.SysDict;
import com.qingzhuge.sys.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : zero.xiao
 * @description :
 * @date :2018/9/20 0020 下午 16:21
 * @modified :
 * @since : 1.0.0
 */
@Slf4j
@Order(2)
@Component
public class SysDictRunner implements ApplicationRunner {
    @Resource
    private ISysDictService dictService;

    @Resource
    private QingTingProperties properties;

    @Override
    public void run(ApplicationArguments args) {
        if (properties.isInitData() || dictService.count() < 1) {
            ISysDictService.Type[] types = ISysDictService.Type.values();
            for (ISysDictService.Type type : types) {
                List<SysDict> sysDicts = dictService.queryByType(type.name());
                if (null == sysDicts || sysDicts.size() == 0) {
                    saveDict(type.getValue(), null, type.name(), type.ordinal(), null);
                }
            }
            for (ISysDictService.Type type : ISysDictService.Type.values()) {
                setDict(type, type.getType());
            }
        }
        dictService.getAllDict();
    }

    private <E extends IBaseEnum<String>> void setDict(ISysDictService.Type ptype, E[] values) {
        List<SysDict> sysDicts = dictService.queryByType(ptype.name());
        if (null != sysDicts && sysDicts.size() > 0) {
            SysDict sysDict = sysDicts.get(0);
            for (E type : values) {
                List<SysDict> dicts = dictService.queryByTypeAndCode(ptype.name(), type.name());
                if (null == dicts || dicts.size() == 0) {
                    saveDict(type.value(), type.name(), sysDict.getType(), type.ordinal(), sysDict.getType());
                }
            }

        }
    }

    private void saveDict(String name, String code, String type, Integer sortBy, String parentType) {
        SysDict dict = new SysDict();
        dict.setType(type);
        if (null != code) {
            dict.setCode(code);
        } else {
            dict.setCode(type);
        }
        dict.setName(name);
        dict.setSortBy(sortBy);
        dict.setParentType(parentType);
        dictService.save(dict);
    }
}